#include <stdio.h>
#include <stdlib.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#include "preloaders.h"
#include "basic_ui.h"
#include "SDL/SDL.h"

#include "chunks/GuacCore_common.h"
#ifdef GUAC_RUN
    #include "chunks/GuacCore_run.h"
#endif
#ifdef GUAC_PUBLISH
    #include "chunks/GuacCore_publish.h"
#endif

int main(int argc, char* argv[])
{
    SDL_Init(0);

    lua_State *L = luaL_newstate();

    // Show fatal errors through an appropriate method for the platform
    lua_atpanic(L, ShowError);

    // Build exec table
    lua_createtable(L, 0, 2);
    {
        // exec.path (path to current executable)
        lua_pushstring(L, argv[0]);
        UpdateAppPath(L);
        lua_setfield(L, -2, "path");

        // exec.args (command-line parameters)
        lua_createtable(L, argc, 0);
        int i;
        for (i=1; i < argc; i++)
        {
            lua_pushstring(L, argv[i]);
            lua_rawseti(L,-2,i);
        }
        lua_setfield(L, -2, "args");
    }
    lua_setglobal(L, "exec");

    // Open standard libraries
    luaL_openlibs(L);

    // Add statically-linked module loaders to the package.preload table
    mole_addpreloaders(L);

    lua_pushcfunction(L, ChooseProject);
    lua_setglobal(L, "requestproject");

    lua_pushcfunction(L, ShowInfo);
    lua_setglobal(L, "showinfo");

    lua_pushcfunction(L, SetIcon);
    lua_setglobal(L, "seticon");

    luaL_loadbuffer(L, chunk_GuacCore_common, sizeof(chunk_GuacCore_common), NULL);
    lua_call(L,0,0);

    #ifdef GUAC_RUN
    luaL_loadbuffer(L, chunk_GuacCore_run, sizeof(chunk_GuacCore_run), NULL);
    lua_call(L,0,0);
    #endif

    #ifdef GUAC_PUBLISH
    luaL_loadbuffer(L, chunk_GuacCore_publish, sizeof(chunk_GuacCore_publish), NULL);
    lua_call(L,0,0);
    #endif

    lua_pushnil(L);
    lua_setglobal(L, "requestproject");

    return 0;
}
